package com.bwie.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bwie.user.dao.GoodsDao;
import com.bwie.user.vo.ActivityVo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.common.utils.PageUtils;
import com.bwie.common.utils.Query;

import com.bwie.user.dao.ActivityDao;
import com.bwie.user.entity.ActivityEntity;
import com.bwie.user.service.ActivityService;


@Service("activityService")
public class ActivityServiceImpl extends ServiceImpl<ActivityDao, ActivityEntity> implements ActivityService {
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    RedissonClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<ActivityEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            wrapper.and(w->{
               w.eq("goods_id",key);
            });
        }
        IPage<ActivityEntity> page = this.page(
                new Query<ActivityEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }
    /**
     * 前台用户活动参与页面
     * redis进行缓存
     * @return
     */
    @Override
    public List<ActivityVo> mslist() {
        //先去redis里查询有没有
        List<ActivityVo> mslist = (List<ActivityVo>) redisTemplate.boundHashOps("map").get("mslist");

        if (mslist!=null){
            System.out.println("mslist,缓存命中");

            return mslist;
        }else {
            RLock lock = client.getLock("lock");

         try {
             boolean b = lock.tryLock();
             if (b){
                 int i=0;
                 List<ActivityVo> activityVos = baseMapper.selectActivityVo();
                 redisTemplate.boundHashOps("map").put("mslist",activityVos);//放入缓存中
                 redisTemplate.expire("map",30,TimeUnit.SECONDS);
                 i++;
                 System.out.println("缓存未命中================"+i);
                 return activityVos;
             }

         } catch (Exception e){
           e.printStackTrace();
         } finally {
              lock.unlock();
         }
        }
            return null;
    }

}